package com.bgs.eat.memberRecord.service.Impl;

import com.bgs.eat.memberRecord.entity.MemberRecordEntity;
import com.bgs.eat.memberRecord.mapper.MemberRecordMapper;
import com.bgs.eat.memberRecord.service.MemberService;
import com.bgs.eat.page.MyPageHelper;
import com.bgs.eat.page.PageRequest;
import com.bgs.eat.page.PageResult;
import com.bgs.eat.utils.RanNum;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @ClassName MemberRecordServiceImpl
 * @Description TODO 购买会员卡记录
 * @Author G胖
 * @Date 2022-10-11 上午 11:23
 **/
@Service
public class MemberRecordServiceImpl implements MemberService {

    @Resource
    MemberRecordMapper memberRecordMapper;

    /**
     * @Author G胖
     * @Description 用户界面--购买超级吃货会员
     * @Date 2022-10-11 下午 07:41
     * @Return com.bgs.eat.config.CommonResult

     */
    @Override
    public Integer buyEatMember(MemberRecordEntity memberRecord) {
        List<MemberRecordEntity> memberRecordEntities = memberRecordMapper.selectUserBuyEatMember(memberRecord.getUserName(),memberRecord.getMemberId());
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        if(!memberRecordEntities.isEmpty()){
            int month = 0;
            for(MemberRecordEntity memberRecordEntity : memberRecordEntities){
                month += memberRecordEntity.getMonth();
            }
            cal.setTime(date);
            cal.add(Calendar.MONTH,month+memberRecord.getMonth());
            memberRecord.setCreateTime(date);
            memberRecord.setExpirationTime(cal.getTime());
            memberRecord.setDelFlag(0);
            memberRecord.setOrderNum(RanNum.createBuyMemberNum());
            return memberRecordMapper.insertSelective(memberRecord);
        }
        else{
            memberRecord.setCreateTime(date);
            cal.setTime(date);
            cal.add(Calendar.MONTH, memberRecord.getMonth());
            memberRecord.setExpirationTime(cal.getTime());
            memberRecord.setDelFlag(0);
            memberRecord.setOrderNum(RanNum.createBuyMemberNum());
            return memberRecordMapper.insertSelective(memberRecord);
        }
    }

    @Override
    public PageResult getMemberRecordByPage(PageRequest pageRequest, String userName, String memberName, String startOpenTime, String overOpenTime) {
        MyPageHelper.startPage(pageRequest);
        Example example = new Example(MemberRecordEntity.class);
        example.createCriteria().andLike("userName","%"+userName+"%").andLike("memberName","%"+memberName+"%")
                .andBetween("createTime",startOpenTime,overOpenTime).andEqualTo("delFlag",0);
        PageResult pageResult = MyPageHelper.pageInfo(memberRecordMapper.selectByExample(example));
        return pageResult;
    }
}
